package insat.challenge.metier;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class DBAdapter {

	DatabaseHelper DBHelper;
	Context context;
	SQLiteDatabase db;

	public DBAdapter(Context context) {
		this.context = context;
		DBHelper = new DatabaseHelper(context);
	}

	public class DatabaseHelper extends SQLiteOpenHelper {

		Context context;

		public DatabaseHelper(Context context) {
			super(context, "contacts", null, 1);
			this.context = context;
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("create table contact (_id integer primary key autoincrement, "
					+ "nomprenom text not null, numTel text not null" + ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Toast.makeText(
					context,
					"Mise à jour de la Base de données version " + oldVersion
							+ " vers " + newVersion, Toast.LENGTH_SHORT).show();
			db.execSQL("DROP TABLE IF EXISTS contact");
			onCreate(db);
		}

	}

	public DBAdapter open() {
		db = DBHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
	}

	public void Truncate() {
		db.execSQL("DELETE FROM contact");
	}

	public long insererUnContact(String nomprenom, String numTel) {
		ContentValues values = new ContentValues();
		values.put("nomprenom", nomprenom);
		values.put("numTel", numTel);
		
		return db.insert("contact", null, values);
	}

	public boolean supprimerContact(long id) {
		return db.delete("contact", "_id=" + id, null) > 0;
	}

	public Cursor recupererLaListeDesContact() {
		return db.query("contact", new String[] { "_id", "nomprenom", "numTel"}, null, null, null, null, null);
	}

}